package com.eascs.pay.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.badloan.service.O2oBadLoanService;
import com.eascs.admin.o2o.generation.service.O2oGenerationService;
import com.eascs.admin.o2o.generation.vo.O2oGenerationVo;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oEaLoanDataEnity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.bankAccount.BankAccountService;
import com.eascs.common.util.StringUtil;
import com.eascs.continueloan.controller.O2oContinueRestController;
import com.eascs.continueloan.service.O2oContinueLoanService;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.ModelResult;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.pay.dao.O2oPayDao;
import com.eascs.pay.entity.O2oPayEntity;
import com.eascs.pay.entity.O2oPayVo;
import com.eascs.pay.form.O2oPayForm;
import com.eascs.pay.form.O2oRefundForm;
import com.eascs.pay.form.O2oRefundWorckForm;
import com.eascs.pay.service.impl.O2oPayServiceImpl;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.WorkFlowConstants;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.type.SystemModule;

@RestController
// @RequestMapping("/pay")
public class O2oPayRestController extends BaseRestController {
	private static Logger log = LoggerFactory.getLogger(O2oPayRestController.class);
	@Autowired
	O2oPayServiceImpl payService;
	@Autowired
	O2oGenerationService generationService;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Reference
	ICustomerInfoService iCustomerInfoService;
	@Autowired
	private BaseUtils baseUtils;
	@Autowired
	O2oContinueLoanService continueLoanService;
	@Autowired
	O2oContinueRestController o2oContinueRestController;
	@Autowired
	private BankAccountService bankAccountService;

	@Autowired
	O2oPayDao payDao;

	/**
	 * 显示分页结果
	 * 
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/query")
	public PaginationRestResult index(O2oPayForm o2oPayForm) {
		int pageSize;
		pageSize = 12;
		PageResult<Object[]> pageResult = null;
		if (0 == o2oPayForm.getPageIndex()) {
			pageResult = new PageResult<>(pageSize, 0, 0);
		} else {
			SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, pageSize, o2oPayForm.getPageIndex());
			StringBuffer sql = new StringBuffer("select bill_code,borrower_name,loanapply_billcode,platform,loan_amount,loan_term,payee_name,pay_type from o2o_pay where 1=1");
			if (StringUtil.hasText(o2oPayForm.getBillCode())) {
				sql.append(" and bill_code=?");
				pageQuery.addParam(o2oPayForm.getBillCode());
			}
			pageQuery.setQuerySql(sql.toString());
			pageResult = payService.findByPage(pageQuery);

		}
		String[] titles = { "单据号", "借款人姓名", "内部审批单号", "经营单位", "借款金额", "借款期限", "收款人", "付款类型" };
		String rendTo = "#action-ajax-load";
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, "/pay/query?pageIndex=", rendTo);
		paginationInfo.setBuildPagingNavigation(true);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	@RequestMapping("/refund/refund_oper")
	public HtmlRestResult refundForm(O2oRefundWorckForm refundForm) {
		log.info("访问付款动态表单开始，贷款单号为：【{}】", refundForm.getReferId());
		O2oPayEntity payEntity = payService.findById(refundForm.getReferId());
		log.info("访问付款动态表单开始，查询付款对象是否为空：【{}】", payEntity);
		ViewContext.put("payEntity", payEntity);
		return HtmlRestResult.html("workflowcheck/refund_oper");
	}

	@RequestMapping("/refund/refund_oper_view")
	public HtmlRestResult refundFormView(O2oRefundWorckForm refundForm) {
		log.info("访问付款动态表单开始，贷款单号为：【{}】", refundForm.getReferId());
		O2oPayEntity payEntity = payService.findById(refundForm.getReferId());
		log.info("访问付款动态表单开始，查询付款对象是否为空：【{}】", payEntity);
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(payEntity.getLoanapplyid());
		ViewContext.put("nodeCode", refundForm.getNodeCode());
		log.info("目前节点是：【{}】", refundForm.getNodeCode());
		ViewContext.put("payEntity", payEntity);
		ViewContext.put("loanEntity", loanEntity);
		getBankAccount();
		return HtmlRestResult.html("workflowcheck/refund_operview");
	}

	public void getBankAccount() {
		List<String> bankcards = bankAccountService.getBankAccount();
		ViewContext.put("bankAccountList", bankcards);
	}

	@RequestMapping("/refund/refund_view")
	public HtmlRestResult refundView(O2oRefundWorckForm refundForm) {
		log.info("访问付款动态表单开始，贷款单号为：【{}】", refundForm.getReferId());
		O2oPayEntity payEntity = payService.findById(refundForm.getReferId());
		ViewContext.put("payEntity", payEntity);
		log.info("访问付款动态表单开始，查询付款对象是否为空：【{}】", payEntity);
		ViewContext.put("nodeCode", refundForm.getNodeCode());
		return HtmlRestResult.html("workflowcheck/refund_oper_view");
	}

	@RequestMapping("/refund/insert")
	public BaseRestResult<String> refundInsert(O2oRefundForm refundForm) {
		try {
			O2oPayEntity payEntitySource = payService.findById(refundForm.getId());
			payEntitySource.setPayeeName(refundForm.getPayeeName());
			payEntitySource.setPayAmount(refundForm.getPayAmount());
			payEntitySource.setCollectionAccount(refundForm.getCollectionAccount());
			payEntitySource.setCollectionBankName(refundForm.getCollectionBankName());
			payEntitySource.setCollectionBankAddress(refundForm.getCollectionBankAddress());
			payEntitySource.setRemark(refundForm.getRemark());
			payEntitySource.setPayRemark(refundForm.getPayRemark());
			payEntitySource.setPayDate(refundForm.getPayDate());
			if (!StringUtils.isEmpty(refundForm.getPayFkType())) {
				payEntitySource.setPayFkType(refundForm.getPayFkType());
			}
			int i = payService.updateEntityById(payEntitySource);
			if (i > 0) {
				ViewContext.put("payEntity", payEntitySource);
				return BaseRestResult.info("保存成功");
			} else {
				return BaseRestResult.info("保存失败");
			}
		} catch (Exception e) {
			log.error("贷款单号为：【{}】的贷款付费表单保存失败。失败原因：{}", refundForm.getId(), e.getStackTrace());
			return BaseRestResult.info("保存失败");
		}
	}

	@RequestMapping("/refund/update")
	public BaseRestResult<String> refundUpdate(O2oRefundForm refundForm) {
		// String isBankno =
		// BankNoCheckUtil.checkBankNo(refundForm.getCollectionAccount());
		// if (isBankno.equals(BankNoCheckUtil.IS1619)) {
		// return BaseRestResult.warn("银行卡号须16到19之间");
		// } else if (isBankno.equals(BankNoCheckUtil.ISNUMBER)) {
		// return BaseRestResult.warn("银行卡号必须全为数字");
		// } else if (isBankno.equals(BankNoCheckUtil.ISNOT)) {
		// return BaseRestResult.warn("银行卡号不符合规范");
		// }
		try {
			O2oPayEntity payEntitySource = payService.findById(refundForm.getId());
			if (refundForm.getNodeCode() != null) { // 有些流程可能没有配置流程节点

				if (refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_DC)) {
					if (StringUtils.isEmpty(refundForm.getLoanType())) {
						return BaseRestResult.warn("代偿类型不能为空");
					}
				}
				if (refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBZJBMFK)) {
					if (refundForm.getPayDate() == null) {
						return BaseRestResult.warn("付款时间不能为空");
					}
				}
				O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(payEntitySource.getLoanapplyid());
				if (loanEntity != null) {
					if ("GACZ".equals(loanEntity.getBankLoanName()) && refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBCWFS)) {
						if (refundForm.getPayDate() == null) {
							return BaseRestResult.warn("付款时间不能为空");
						}
					}
				}

				if (refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBCWFS) || refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBZJBMFK)) {
					if (StringUtils.isEmpty(refundForm.getPayFkType())) {
						return BaseRestResult.warn("付款类型不能为空");
					}
				}

				if (refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBCWFS) || refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_CWCS)) {
					if (refundForm.getPayFkType().equals(StatusContexts.PAYMENT_TYPE_XF)) {
						log.info("付款类型为虚付={}，付款账号={}，流程类型={}", refundForm.getPayFkType(), refundForm.getPayFkAccount(), refundForm.getNodeCode());
						log.info("虚付进入付款账号校验={}", refundForm.getPayFkAccount());
						if (StringUtils.isEmpty(refundForm.getPayFkAccount())) {
							return BaseRestResult.warn("付款账号不能为空");
						}
					}
					// else if
					// (refundForm.getPayFkType().equals(StatusContexts.PAYMENT_TYPE_SF))
					// {
					// log.info("付款类型为实付={}，付款账号={}", refundForm.getPayFkType(),
					// refundForm.getPayFkAccount());
					// log.info("实付进入付款账号校验={}", refundForm.getPayFkAccount());
					// if (StringUtils.isEmpty(refundForm.getPayFkAccount())) {
					// return BaseRestResult.warn("付款账号不能为空");
					// }
					// }
				} else if (refundForm.getNodeCode().equals(WorkFlowConstants.WORKFLOW_NODECODE_FK_GBZJBMFK)) {
					// if
					// (refundForm.getPayFkType().equals(StatusContexts.PAYMENT_TYPE_XF))
					// {
					// log.info("付款类型为虚付={}，付款账号={}，流程类型={}",
					// refundForm.getPayFkType(), refundForm.getPayFkAccount(),
					// refundForm.getNodeCode());
					// log.info("虚付进入付款账号校验={}", refundForm.getPayFkAccount());
					// if (StringUtils.isEmpty(refundForm.getPayFkAccount())) {
					// return BaseRestResult.warn("付款账号不能为空");
					// }
					// } else
					if (refundForm.getPayFkType().equals(StatusContexts.PAYMENT_TYPE_SF)) {
						log.info("付款类型为实付={}，付款账号={}", refundForm.getPayFkType(), refundForm.getPayFkAccount());
						log.info("实付进入付款账号校验={}", refundForm.getPayFkAccount());
						if (StringUtils.isEmpty(refundForm.getPayFkAccount())) {
							return BaseRestResult.warn("付款账号不能为空");
						}
					}
				}

			}
			log.info("代偿类型={},{}，付款类型={}", refundForm.getLoanType(), refundForm.getNodeCode(), refundForm.getPayFkType());
			if (!StringUtils.isEmpty(refundForm.getLoanType())) {
				payEntitySource.setLoanType(refundForm.getLoanType());
			}
			payEntitySource.setPayeeName(refundForm.getPayeeName());
			payEntitySource.setPayAmount(refundForm.getPayAmount());
			payEntitySource.setPayFkAccount(refundForm.getPayFkAccount());
			payEntitySource.setCollectionAccount(refundForm.getCollectionAccount());
			payEntitySource.setCollectionBankName(refundForm.getCollectionBankName());
			payEntitySource.setCollectionBankAddress(refundForm.getCollectionBankAddress());
			payEntitySource.setRemark(refundForm.getRemark());
			payEntitySource.setPayRemark(refundForm.getPayRemark());
			payEntitySource.setPayDate(refundForm.getPayDate());
			if (!StringUtils.isEmpty(refundForm.getPayFkType())) {
				payEntitySource.setPayFkType(refundForm.getPayFkType());
			}
			int i = payService.updateEntityById(payEntitySource);
			if (i > 0) {
				ViewContext.put("payEntity", payEntitySource);
				return BaseRestResult.info("保存成功");
			} else {
				return BaseRestResult.warn("保存失败");
			}
		} catch (

		Exception e)

		{
			log.error("贷款单号为：【{}】的贷款付费表单保存失败。失败原因：{}", refundForm.getId(), e.getStackTrace());
			return BaseRestResult.warn("保存失败");
		}

	}

	@RequestMapping("/rpay/detail")
	public BaseRestResult<String> detail(String id) {
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (o2oPayEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		O2oPayEntity payEntity = getUserIdNumber(o2oPayEntity);
		if (payEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(id, null, SystemModule.SYSTEM_MODULE_O2O);
		String agreeUrl1 = baseUtils.getApprovalAgreeUrl(payEntity.getLoanapplyid(), null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl1", agreeUrl1);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", payEntity);
		return HtmlRestResult.popHtmlFragment("pay/detail");
	}

	@Autowired
	private O2oBadLoanService service;

	@RequestMapping("/rpay/pay_info_common")
	public BaseRestResult<String> payInfoCommon(String id) {
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (null == o2oPayEntity) {
			// 查询不良放款
			O2oEaLoanDataEnity dataEnity = service.findById(id);
			if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getPayId())) {
				o2oPayEntity = payService.findById(dataEnity.getPayId());
			} else if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getBillCodeEa())) {
				o2oPayEntity = payService.findDetailByOaBillCode(dataEnity.getBillCodeEa());
			}
		}
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(o2oPayEntity.getLoanapplyid());
		ViewContext.put("entity", o2oPayEntity);
		ViewContext.put("loanEntity", loanEntity);
		return new HtmlRestResult("pay/pay_info_common");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               脱敏查看弹窗
	 *               </p>
	 * @author LMX
	 */
	@RequestMapping("/rpay/show_window")
	public BaseRestResult<String> showWindow(String id) {
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (null == o2oPayEntity) {
			// 查询不良放款
			O2oEaLoanDataEnity dataEnity = service.findById(id);
			if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getPayId())) {
				o2oPayEntity = payService.findById(dataEnity.getPayId());
			} else if (dataEnity != null && !StringUtils.isEmpty(dataEnity.getBillCodeEa())) {
				o2oPayEntity = payService.findDetailByOaBillCode(dataEnity.getBillCodeEa());
			}
		}
		ViewContext.put("entity", o2oPayEntity);
		return HtmlRestResult.popHtmlFragment("pay/pay_info_sensitive");
	}

	@RequestMapping("/myrpay/detail")
	public BaseRestResult<String> mydetail(String billCode) {
		String sql = "select id from o2o_pay where bill_code= ? ";
		O2oPayEntity PayEntity = payDao.findEntity(sql, O2oPayEntity.class, billCode);
		String id = PayEntity.getId();
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (o2oPayEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		O2oPayEntity payEntity = getUserIdNumber(o2oPayEntity);
		if (payEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(id, null, SystemModule.SYSTEM_MODULE_O2O);
		String agreeUrl1 = baseUtils.getApprovalAgreeUrl(payEntity.getLoanapplyid(), null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl1", agreeUrl1);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", payEntity);
		return HtmlRestResult.popHtmlFragment("pay/detail");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               启动付款流程
	 *               </p>
	 * @author CXW
	 * @date 2017年1月16日 下午1:30:00
	 * @version V1.0
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/rpay/startPay")
	public BaseRestResult<String> startPay(String id) {
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (o2oPayEntity == null) {
			return BaseRestResult.warn("数据异常，请联系运维人员");
		}
		// 加一个是否有垫付流程在运行中的判断
		O2oPayEntity checko2oPayEntity = new O2oPayEntity();
		checko2oPayEntity.setLoanapplyBillcode(o2oPayEntity.getBillCode());
		checko2oPayEntity.setBillStatus(StatusContexts.WFTYPE_STATUS_RUN);
		checko2oPayEntity.setPayType(StatusContexts.PAY_TYPE_DF);
		checko2oPayEntity.setIsdel(StatusContexts.O2O_NO);
		boolean ishaspay = payService.isHaveRUNPayFlow(checko2oPayEntity);
		if (ishaspay) {
			return BaseRestResult.warn("已经有一个付费流程在流程中，请勿重复启动");
		}
		User user = UserHolder.getUser();
		O2oLoanapplyEntity loanEntity = null;
		loanEntity = o2oLoanapplyService.fingByBillCode(o2oPayEntity.getBillCode());
		loanEntity.setRepaymentSource(StatusContexts.DATA_SOURCE_NEW);
		loanEntity.setOperatorNo(user.getNo());
		loanEntity.setOperatorName(user.getCname());
		try {
			com.eascs.workflow.common.vo.ModelResult<Boolean> model = payService.startPayFlowFx(loanEntity, o2oPayEntity.getBorrowerName());
			if (model.isSuccess()) {
				log.info("垫付启动付款流程数据成功，贷款单号为：{}", loanEntity.getLoanapplyNo());
				if (null != o2oPayEntity) {
					o2oPayEntity.setSubmitTime(new Date());
					o2oPayEntity.setSubmitUser(loanEntity.getOperatorNo());
					o2oPayEntity.setBillStatus(StatusContexts.O2O_BANK_RUN);
					o2oPayEntity.setLastUpdateTime(new Date());
					payService.updateEntityById(o2oPayEntity);
					log.info("垫付启动付款流程数据成功，贷款单号为：{},更新付款数据成功", loanEntity.getLoanapplyNo());
					return BaseRestResult.info("垫付流程启动成功").andRefresh();
				}
			} else {
				log.error("垫付启动付款流程数据失败，贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), model.getErrMsg());
				return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + model.getErrMsg());
			}
		} catch (Exception e) {
			log.error("error垫付插入启动付款流程数据失败,贷款单号为：{},失败原因：{}", loanEntity.getLoanapplyNo(), e.getMessage());
			return BaseRestResult.warn("垫付流程启动失败，请联系管理员。失败原因：" + e.getMessage());
		}
		return BaseRestResult.warn("垫付流程启动异常");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据终端贷贷款单号查询直贷和垫付多少笔（列表）
	 *               </p>
	 * @author CXW
	 * @date 2016年10月27日 上午11:13:52
	 * @version V1.0
	 * @param billCode
	 *            终端贷贷款单号
	 */
	@RequestMapping("/rpay/list")
	public BaseRestResult<String> list(String billCode) {
//		List<O2oPayEntity> o2oPayEntity = payService.findByBillCodeList(billCode);// 查借款金额
		List<O2oPayEntity> o2oPayEntity = payService.findByBillCodeList_OL(billCode);//【查放款金额（银行批复额度）OL.bank_amount as LOAN_AMOUNT】
		ViewContext.put("entitys", o2oPayEntity);
		return HtmlRestResult.html("pay/list");
	}
	
	/**
	 * @Description:
	 *               <p>
	 *               脱敏查看弹窗
	 *               </p>
	 * @author LMX
	 */
	@RequestMapping("/rpay/list_show_window")
	public BaseRestResult<String> listShowWindow(String billCode) {
		List<O2oPayEntity> o2oPayEntity = payService.findByBillCodeList_OL(billCode);//【查放款金额（银行批复额度）OL.bank_amount as LOAN_AMOUNT】
		ViewContext.put("entitys", o2oPayEntity);
		return HtmlRestResult.popHtmlFragment("pay/list_sensitive");
	}

	@RequestMapping("/rpay/print")
	public BaseRestResult<String> print(String id) {
		O2oPayEntity o2oPayEntity = payService.findById(id);
		if (o2oPayEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		O2oPayEntity payEntity = getUserIdNumber(o2oPayEntity);
		if (payEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(id, null, SystemModule.SYSTEM_MODULE_O2O);
		Date date = new Date();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		ViewContext.put("printDate", s.format(date));
		String agreeUrl1 = baseUtils.getApprovalAgreeUrl(payEntity.getLoanapplyid(), null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl1", agreeUrl1);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", payEntity);
		return HtmlRestResult.popHtmlFragment("pay/print");
	}

	public O2oPayEntity getUserIdNumber(O2oPayEntity o2oPayEntity) {
		O2oPayEntity payEntity = null;
		if (null != o2oPayEntity) {
			if (!StringUtil.isEmpty(o2oPayEntity.getResourseFrom()) && o2oPayEntity.getResourseFrom().equals(StatusContexts.DATA_SOURCE_OLD)) {
				payEntity = payService.findDetailByOaBillCode(o2oPayEntity.getLoanapplyBillcode());
				String id = "";
				ModelResult<String> modelResult = iCustomerInfoService.getCustomerByBillCode(o2oPayEntity.getBillCode());
				log.info("调用CRM接口是否成功：{}", modelResult.isSuccess());
				if (modelResult.isSuccess()) {
					id = modelResult.getModel();
					if (StringUtil.isEmpty(id) || "-1".equals(id) || "-2".equals(id) || "-3".equals(id)) {
						log.warn("调用CRM接口返回用户id为：{}", id);
						return null;
					}
				} else {
					log.warn("调用CRM接口失败，原因：{}", modelResult.getErrMsg());
					return null;
				}
				QueryCustomerVO vo = new QueryCustomerVO();
				vo.setCustomer_id(id);
				log.info("调用CRM用户接口开始，参数：{}", vo.getCustomer_id());
				CustomerView customer = iCustomerInfoService.geCustomerView(vo);
				log.info("在CRM中查询数据结果：用户信息{},资产信息{},配偶信息{},门店信息{}", customer.getBasicInfo(), customer.getAssetInfo(), customer.getExpansionInfo(), customer.getShopInfoList());
				CustomerBasicInfoEntity basicEntity = customer.getBasicInfo();
				if (basicEntity == null) {
					return null;
				}
				payEntity.setPlatform(payEntity.getPlatformName());
				payEntity.setBorrowerId(basicEntity.getIdNumber());
			} else {
				payEntity = payService.findById(o2oPayEntity.getId());
			}
		}
		return payEntity;
	}

	@RequestMapping("/rpay/pay_approval")
	public BaseRestResult<String> payApprola(O2oPayVo vo) {
		O2oPayEntity o2oPayEntity = payService.findById(vo.getReferId());
		if (o2oPayEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		O2oPayEntity payEntity = getUserIdNumber(o2oPayEntity);
		if (payEntity == null) {
			return BaseRestResult.warn("未查询到付款单号，请联系管理员");
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(vo.getReferId(), null, SystemModule.SYSTEM_MODULE_O2O);
		String approvalUrl = baseUtils.getApprovalUrl(vo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(payEntity.getLoanapplyid());
		ViewContext.put("loanEntity", loanEntity);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", payEntity);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", vo.getApprovalStatus());
		return HtmlRestResult.popHtmlFragment("approval/pay_approval");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示添加页面
	 *               </p>
	 * @author yy
	 * @date 2017年6月7日 下午5:07:46
	 * @version V1.0
	 */
	@RequestMapping("/pay/add_view")
	public BaseRestResult<String> addView(O2oGenerationVo vo) {

		return HtmlRestResult.popHtmlFragment("pay/add_view");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               显示编辑页面
	 *               </p>
	 * @author LMX
	 * @date 2017年8月18日
	 * @version V1.0
	 */
	@RequestMapping("/pay/edit_view")
	public BaseRestResult<String> editView(O2oGenerationVo gvo) {
		O2oPayEntity o2oPayEntity = payService.findById(gvo.getId());
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.fingByBillCode(gvo.getLoanBillCode());
		ViewContext.put("loanEntity", loanEntity);
		ViewContext.put("o2oPayEntity", o2oPayEntity);
		return HtmlRestResult.popHtmlFragment("pay/edit_view");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               保存
	 *               </p>
	 * @author yy
	 * @date 2017年6月7日 下午5:07:30
	 * @version V1.0
	 */
	@RequestMapping("/pay/saves")
	public BaseRestResult<String> save(O2oGenerationVo entity, String type, String payFkType) {
		if (StringUtils.isEmpty(payFkType)) {
			return BaseRestResult.warn("请填写付款类型");
		}
		if (StringUtils.isEmpty(entity.getLoanBillCode())) {
			return BaseRestResult.warn("请填写贷款单号");
		}
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.fingByBillCode(entity.getLoanBillCode());
		if (loanEntity == null) {
			return BaseRestResult.warn("单款单不存在");
		}
		// 只有已放款的单能够垫付
		if (!loanEntity.getWfType().equals(StatusContexts.O2O_FK_END) && !loanEntity.getWfType().equals(StatusContexts.OVERDUE_YQ)) {
			return BaseRestResult.warn("该单不是已放款或逾期状态，无法垫付");
		}
		// 只能垫付借款热嗯最新的一笔
		O2oLoanapplyEntity LoanapplyNew = o2oLoanapplyService.fingLoanapplyNewByloanId(loanEntity.getLoanId());
		if (LoanapplyNew == null) {
			return BaseRestResult.warn("借款人不存在贷款单");
		} else {
			if (!loanEntity.getLoanapplyNo().equals(LoanapplyNew.getLoanapplyNo())) {
				return BaseRestResult.warn("该借款单不是该借款人最近的贷款单，无法垫付。");
			}
		}

		if (type.equals("SAS")) { // 保存并提交
			BaseRestResult<String> modelResult = o2oContinueRestController.dfloanFx("NEW", entity.getLoanBillCode(), payFkType, StatusContexts.LOAN_TYPE_FQ, entity.getId());
			return BaseRestResult.info(modelResult.getMessage()).andRefresh();
		} else { // 保存
			BaseRestResult<String> modelResult = o2oContinueRestController.dfloanFx("NEW", entity.getLoanBillCode(), payFkType, null, entity.getId());
			return BaseRestResult.info(modelResult.getMessage()).andRefresh();
		}
	}

	@RequestMapping("/loanDetail/test")
	public BaseRestResult<String> test() {

		return BaseRestResult.info("调用成功");
	}
}
